var nowDate = getDay(0);
var pandianid = GetQueryString('pandianid');
var shopcode = GetQueryString("shopcode");
if(shopcode == null || shopcode == undefined || shopcode == ''){
	shopcode = sessionStorage.getItem("shopcode");
}
//alert(shopcode);
var shopname = sessionStorage.getItem("shopname");
//alert(shopname)
var userId = sessionStorage.getItem("userId");
var type = GetQueryString("type");//页面类型 chakan,fankui,huifu,xiugai,wancheng
var thenum = 0;
var corp = GetQueryString('corp')==null?"":GetQueryString('corp');
if(corp==''){
	corp = sessionStorage.getItem("corp");
}else{
	sessionStorage.setItem("corp",corp);
}
var _config ;
$.ajax({
	type : "post",
	data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26'),"corp":sessionStorage.getItem("corp")}),
	contentType: "application/json; charset=utf-8",
	async: false,
	url : "../../dingding/getconfig",
	dataType : "json",
	success : function(suc) {
		console.log(suc);
		_config = suc.config;
	}
}); 
dd.config({
	agentId : _config.agentid,
	corpId : _config.corpId,
	timeStamp : _config.timeStamp,
	nonceStr : _config.nonceStr,
	signature : _config.signature,
	jsApiList : [ 'runtime.info','biz.util.uploadImage','biz.contact.complexPicker','biz.customContact.choose' ]
});
function ICalendarClick(){
	
}
if(sessionStorage.getItem("name")){
	//alert(localStorage.getItem("name"));
//	setthenum();

	onload();
}else{

	dd.ready(function() {
		//channel runtime  requestOperateAuthCode requestAuthCode
	    dd.runtime.permission.requestAuthCode({
	        corpId: _config.corpId,
	        onSuccess: function(result) {
	        	getuserId(result);
	        },
	        onFail : function(err) {
	        	alert("错误"+JSON.stringify(err))
	        }
	 
	    });
	});
	function getuserId(result){
			    //$("body").text('https://oapi.dingtalk.com/user/getuserinfo?code=' + result.code + '&access_token='+ _config.token);
		$.ajax({
			url : '../../dingding/ddEasy',
			type : 'POST',
			data:JSON.stringify({"code":result.code,"token":_config.token}),
			contentType: "application/json; charset=utf-8",
			dataType : "json",
			success : function(suc) {
			    if(suc.status == '1002'){
			    	sessionStorage.setItem("userId",suc.userJson.userid);
			    	sessionStorage.setItem("name",suc.userJson.name);
			    	sessionStorage.setItem("jobnumber",suc.userJson.jobnumber);
			    	sessionStorage.setItem("deptId",suc.userJson.department);
			    	userId = sessionStorage.getItem("userId");
//					setthenum();
			    	onload();
			    }else{
			    	layer.alert(suc.msg);
			    }

			},
			error : function(xhr, errorType, error) {
					alert(errorType + ', ' + error);
				}
		});
	}
	dd.error(function(err) {
		alert('dd error: ' + JSON.stringify(err));
	});
}
function onload(){
/*	alert(sessionStorage.getItem("reload"));*/
	$('#shopcodeshow').text(shopcode)
	getShopname();
    if(sessionStorage.getItem("reload")=='true'){
	     window.location.reload();
		sessionStorage.setItem("reload", false);
		console.log("reload"); 
	}else{
		getPandianJianchaWentifankui();
		$('#name').text(sessionStorage.getItem("name"));
		$('#addButton').on('click',addform);
		$(document).on('click','div[deleteIndex]',function(){
			var obj = this;
//			editInfo($(obj).attr('deleteIndex'),'delete')
			dd.ready(function(){
				dd.device.notification.confirm({
					message: "确认删除此条款吗？",
					title: "提示",
					buttonLabels: ['是', '否'],
					onSuccess : function(result) {
						//onSuccess将在点击button之后回调
						/*
			        {
			            buttonIndex: 0 //被点击按钮的索引值，Number类型，从0开始
			        }
						 */
						if(result.buttonIndex == 0){
//							$('div[itemDiv="'+$(obj).attr('deleteIndex')+'"]').remove();
							editInfo($(obj).attr('deleteIndex'),'delete')
						}
					},
					onFail : function(err) {}
				});
			})
		});
		$(document).on('click','div[editIndex]',function(){
			var obj = this;
//			editInfo($(obj).attr('editIndex'),'edit')
			dd.ready(function(){
				dd.device.notification.confirm({
					message: "确认编辑此条款吗？",
					title: "提示",
					buttonLabels: ['是', '否'],
					onSuccess : function(result) {
						//onSuccess将在点击button之后回调
						/*
			        {
			            buttonIndex: 0 //被点击按钮的索引值，Number类型，从0开始
			        }
						 */
						if(result.buttonIndex == 0){
//							$('div[itemDiv="'+$(obj).attr('deleteIndex')+'"]').remove();
							editInfo($(obj).attr('editIndex'),'edit')
						}
					},
					onFail : function(err) {}
				});
			})
		});
	
	}
	
	
};
function getPandianJianchaWentifankui(){
	showloading();
	var sendData = {};
	sendData.pandianid = pandianid;
	if(type == 'huifu'){
		sendData.flag = 0;
		sendData.senduser = userId;
	}
	if(type == 'wancheng'){
		sendData.flag = 2;
		sendData.wanchenguser = userId;
	}
	$.ajax({
		url: "../pandianevery/getPandianJianchaWentifankui"
		,type:'post'
		,dataType:'json'
		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify(sendData) 
		,success: function(res){
			console.log(res)
			try {
				if(res.success){
					var data = res.data;
					thenum = 0;
					$('#f_div').empty();
					if(data == undefined || data.length < 1){
						if(type != 'huifu'){
							addform();
							addoperation();
						}
						
					}else{
						addPandianJianchaWentifankui(data);
						if(type == 'xiugai'){
							addoperation()
						}
					}
				}else{
					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
	    });
}
function saveInfo(){
	showloading();
	try {
		var imgStr = "";
		var sendData = {};
		var insertArray = [];
		var checkFlag = true;
		$('div[itemDiv]').each(function(i,obj){
			if(checkFlag){
				var insertJson = {};
				$(obj).find('[jsonKey]').each(function(j,el){
					if($(el).parent().find('span').text() == '*' && $(el).val() == ''){
						alert($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('jsonKey');
						insertJson[key] = $(el).val();
						//console.log(insertJson);
						key = null;
					}
				});
				if(insertJson.wenti == ''){
					alert("问题反馈不能为空");
					checkFlag = false;
					return false;
				}
				//设置图片
				if(checkFlag){
					var img = [];
					$(obj).find('img[wentiimg]').each(function(j,el){
						img.push($(el).attr('src'));
					});
					insertJson.imgurl = img;
				}
				if(insertJson.id == undefined){
					insertJson.pandianid = pandianid;
					insertJson.lrr = userId;
					insertJson.flag = 0;
					insertJson.shopcode = sessionStorage.getItem("shopcode");
					insertJson.shenpiFlag = '';
					insertArray.push(insertJson);
				}
			}else{
				return false;
			}
		});
//		console.log(sendData);
		if(checkFlag && insertArray.length > 0){
			sendData.dataArray = insertArray;
			$.ajax({
				url: "../pandianevery/insertPandianJianchaWentifankui"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.success){
						history.go(-1);
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	
	
}	

function editInfo(itemIndex,opeType){
	var itemDiv = $('div[itemDiv="'+itemIndex+'"]');
	var id = itemDiv.find('input[jsonKey="id"]');
	
	var insertJson = {};
	//证明是可以编辑的，删除也需要从后台删除，不能真正删除，修改为禁用就行
	if(id.length == 1){
		var checkFlag = true;
		$(itemDiv).find('[jsonKey]').each(function(j,el){
			if($(el).parent().find('span').text() == '*' && $(el).val() == ''){
				layer.alert($(el).parent().find('h5').text()+"为必填项");
				checkFlag = false;
				return false;
			}else{
				var key = $(el).attr('jsonKey');
				insertJson[key] = $(el).val();
				//console.log(insertJson);
				key = null;
			}
		});
		if(checkFlag && insertJson.id != ''){
			showloading();
			if(opeType == 'delete'){
				insertJson.flag = 1;
				$('div[itemDiv="'+itemIndex+'"]').remove();
			}
			insertJson.userId=sessionStorage.getItem("userId");
			$.ajax({
				url: "editPandianShopDaiban"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(insertJson) 
				,success: function(res){
					if(res.success){
						location.reload();
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}else{
			return false;
		}
	}else{
		$('div[itemDiv="'+itemIndex+'"]').remove();
	}
}
//获取门店名称
function getShopname(){
	 if(shopname != null && shopname != 'null' && shopname != undefined && shopname != '' && shopname != 'undefined'){
		 $('#html_type').text(shopname)
	 }else{
		 $.ajax({
				url: "../pandianevery/getPandianJiancha"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify({'id':pandianid}) 
				,success: function(res){
					if(res.success){
						var data = res.data[0];
						 $('#html_type').text(data.shopname);
					}
				}
		    });
	 }
}
function addform(){
	var huifuEl = "";
	
	var itemDivIndex = $('div[itemDiv]').length;
    $('#f_div').append('<div class="col_box" itemDiv="'+thenum+'">'
    					+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
						+'<h5 id="wentishuomingTitle" class="black">问题反馈'+(itemDivIndex+1)+'</h5>'
						+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
						+'</div>'
						+'		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;问题说明</h5><span class="red">*</span>'
//						+'				<input type="text" id="wenti'+thenum+'" placeholder="请输入问题反馈" jsonKey="wenti" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
						+'			</div>'
						+'			<div class="widget-body zhediebox1">'					
						+'				<div class="widget-main pd_div" style="padding:0;">'					
						+'					<div class="clearfix jy_div" style="padding:0;">'						
						+'						<textarea id="wenti'+thenum+'" rows="6" jsonKey="wenti" name="wenti'+thenum+'" class="pull-left add_pad_tb10p add_bor_none" placeholder="输入问题"></textarea>'								
						+'					</div>'						
						+'				</div>'						
						+'			</div>'
						+'		</div>'
						+'		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
						+'				<h5><i class="iconfont">&#xe61e;</i>&nbsp;发送到人</h5><span class="red">*</span>'
						+'				<input type="text" id="sendusername'+thenum+'" readonly="readonly" placeholder="请选择" onclick="openDingdingUser('+thenum+')" jsonKey="sendusername" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
						+'				<input type="hidden" id="senduser'+thenum+'" jsonKey="senduser"/>'
						+'			</div>'
						+'		</div>'
						+'		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;图片上传</h5><span class="red"></span>'						  
						+'				<div class="widget-toolbar no-border" style="margin-top: 5px" onclick="openphoto('+thenum+')">'
						+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
						+'				</div>'
						+'			</div>'				
						+'			<div class="widget-body zhediebox1">'					
						+'				<div class="widget-main pd_div" id="paizhapoUrl'+thenum+'">'
						
						+'					<div class="clearfix"></div>'						
						+'				</div>'						
						+'			</div>'					
						+'		</div>'
						+'</div>');					
	
    thenum++;
}

function addPandianJianchaWentifankui(jsonparse){
	for(var i = 0 ;i<jsonparse.length;i++){
		var thenum = jsonparse[i].id;
		var imgStr = '';
		var img = typeof jsonparse[i].imgurl=='string'?JSON.parse(jsonparse[i].imgurl):jsonparse[i].imgurl;
		for (var j = 0; j < img.length; j++) {
			imgStr += '<div class="wig_img">'
				+'<div class="img_box">'
				+'<img wentiimg alt="100x100" src="'+img[j]+'" onclick="showAllPic(\''+img[j]+'\')"/>'
				+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
				+'</div>'
				+'</div>'
		}
		var chakanStr = '',huifuButton='';
		if(type != 'xiugai'){
			chakanStr += '		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;回复内容</h5><span class="red"></span>'						  
						+'			</div>'				
						+'			<div class="widget-body zhediebox1">'					
						+'				<div class="widget-main pd_div" style="padding:0;">'					
						+'					<div class="clearfix jy_div" style="padding:0;">'						
						+'						<textarea id="huifu'+thenum+'" rows="6" jsonKey="huifu" readonly name="huifu'+thenum+'" rows="" cols="" class="pull-left add_pad_tb10p add_bor_none" placeholder="输入回复内容"></textarea>'								
						+'					</div>'						
						+'				</div>'						
						+'			</div>'					
						+'		</div>';
		}
		if(type != "huifu" && type != 'xiugai'){
			chakanStr +='		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;回复人</h5><span class="red"></span>'
						+'				<input type="text" id="huifuusername'+thenum+'" readonly="readonly" placeholder="" jsonKey="huifuusername" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
						+'				<input type="hidden" id="huifuuser'+thenum+'" readonly="readonly" jsonKey="huifuuser"/>'
						+'			</div>'
						+'		</div>'
//						+'		<div class="widget-box add_mar_tb7p">'
//						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
//						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;回复状态</h5><span class="red"></span>'
//						+'				<select id="flag'+thenum+'" jsonKey="flag" class="pull-right add_bor_none" style="width: 70%;margin-right: 2%;">'
//						+'				 <option value ="0">未回复</option>'
//						+'				 <option value ="1">已回复</option>'
//						+'				</select> ' 
//						+'			</div>'
//						+'		</div>'
						+'		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;回复时间</h5><span class="red"></span>'
						+'				<input type="text" id="huifudate'+thenum+'" readonly="readonly" placeholder="" jsonKey="huifudate" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
						+'			</div>'
						+'		</div>';
		}
		var huifuImgButton='';
		if(type == 'huifu' && jsonparse[i].flag == '0'){
			huifuButton = '<div class="buttonbox"><div style="width: 49%;margin-right: 2%;float: left;" onclick="huifu('+thenum+',1)" class="submit_button">完成</div><div style="width: 49%;float: right;" onclick="huifu('+thenum+',2)" class="submit_button">回复</div></div>';
			huifuImgButton = '				<div class="widget-toolbar no-border" style="margin-top: 5px"  onclick="openphotohuifu('+thenum+')">'
							+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
							+'				</div>'
		}
		if(type == 'wancheng'){
			huifuButton = '<div class="buttonbox"><div onclick="huifu('+thenum+',1)" class="submit_button w94">完成</div>></div>';
		}
		
		if(type == 'huifu' || type == 'wancheng'){
			var xuanzewanchenguser = "";
			if(type == 'huifu'){
				xuanzewanchenguser = ' onclick="openwanchengUser('+thenum+')"';
			}
			var huifuImgStr = '';
			var huifuImg = jsonparse[i].huifuImg;
			if(huifuImg != undefined){
				huifuImg = typeof jsonparse[i].huifuImg=='string'?JSON.parse(jsonparse[i].huifuImg):jsonparse[i].huifuImg;
				for (var j = 0; j < huifuImg.length; j++) {
					huifuImgStr += '<div class="wig_img">'
						+'<div class="img_box">'
						+'<img huifuimg alt="100x100" src="'+huifuImg[j]+'" onclick="showAllPic(\''+huifuImg[j]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						+'</div>'
				}
			}
			chakanStr += '		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;回复图片上传</h5><span class="red"></span>'						  
//						+'				<div class="widget-toolbar no-border" style="margin-top: 5px"  onclick="openphoto('+thenum+')">'
//						+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
//						+'				</div>'
				+huifuImgButton
				+'			</div>'				
				+'			<div class="widget-body zhediebox1">'					
				+'				<div class="widget-main pd_div" id="paizhaoHuifuUrl'+thenum+'">'
				+huifuImgStr
				+'					<div class="clearfix"></div>'						
				+'				</div>'						
				+'			</div>'					
				+'		</div>';
			chakanStr += '		<div class="widget-box add_mar_tb7p">'
							+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
							+'				<h5><i class="iconfont">&#xe609;</i>&nbsp;预计完成时间</h5><span class="red"></span>'
							+'					<input type="text" id="planDate'+thenum+'" readonly="readonly" placeholder="请选择预计完成时间" jsonKey="planDate" class="pull-right add_bor_none" autocomplete="off" style="width: 60%;margin-right: 2%;"/>'
							+'			</div>'
							+'		</div>'
							+'		<div class="widget-box add_mar_tb7p">'
							+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
							+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;完成人</h5><span class="red"></span>'
							+'				<input type="text" id="wanchengusername'+thenum+'" readonly="readonly" placeholder=""'+xuanzewanchenguser+' jsonKey="wanchengusername" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
							+'				<input type="hidden" id="wanchenguser'+thenum+'" readonly="readonly" jsonKey="wanchenguser"/>'
							+'			</div>'
							+'		</div>'
		}
		var itemDivIndex = $('div[itemDiv]').length;
		$('#f_div').append('<div class="col_box" itemDiv="'+thenum+'">'
				+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
				+'<h5 id="wentishuomingTitle" class="black">问题反馈'+(itemDivIndex+1)+'</h5>'
//				+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
				+'</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;问题说明</h5><span class="red"></span>'
//				+'				<input type="text" id="wenti'+thenum+'" readonly="readonly" placeholder="请输入问题说明" jsonKey="wenti" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'			</div>'
				+'			<div class="widget-body zhediebox1">'					
				+'				<div class="widget-main pd_div" style="padding:0;">'					
				+'					<div class="clearfix jy_div" style="padding:0;">'						
				+'						<textarea id="wenti'+thenum+'" rows="6" jsonKey="wenti" readonly="readonly" name="wenti'+thenum+'" class="pull-left add_pad_tb10p add_bor_none" placeholder="输入问题说明"></textarea>'								
				+'					</div>'						
				+'				</div>'						
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe61e;</i>&nbsp;发送到人</h5><span class="red"></span>'
				+'				<input type="text" id="sendusername'+thenum+'" readonly="readonly" onclick="openDingdingUser('+thenum+')" placeholder="请选择" jsonKey="sendusername" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'				<input type="hidden" id="senduser'+thenum+'" jsonKey="senduser"/>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;图片上传</h5><span class="red"></span>'						  
//				+'				<div class="widget-toolbar no-border" style="margin-top: 5px"  onclick="openphoto('+thenum+')">'
//				+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
//				+'				</div>'
				+'			</div>'				
				+'			<div class="widget-body zhediebox1">'					
				+'				<div class="widget-main pd_div" id="paizhapoUrl'+thenum+'">'
				+imgStr
				+'					<div class="clearfix"></div>'						
				+'				</div>'						
				+'			</div>'					
				+'		</div>'
				+chakanStr
				+'<input type="hidden" id="id'+thenum+'" value="'+jsonparse[i].id+'" jsonKey="id"/>'
//				+'<div editIndex="'+thenum+'" class="bt_delete bg_blue">编辑</div><div class="clearfix"></div>'
				+huifuButton
				+'</div>'
				);
		if(type == 'huifu'){
			var planDatecalendar = new lCalendar();
			planDatecalendar.init({
				'trigger': '#planDate'+thenum,
				'type': 'datetime',
				'maxDate': '2099-12-31 23:59',
				'minDate':  nowDate+' 00:00'
			});
			$('#huifu'+thenum).removeAttr('readonly');
		}
		if(type == 'xiugai'){
			$('#wenti'+thenum).removeAttr('readonly');
		}
		//设置值
		for(var el in jsonparse[i]){
			$('#'+el+thenum).val(jsonparse[i][el])
		}
	}
}

function huifu(fankuiid,huifuFlag){
	showloading();
	try {
		var sendData = {};
		sendData.huifuusername = sessionStorage.getItem("name");
		sendData.huifu = $('#huifu'+fankuiid).val();
		sendData.flag = huifuFlag;
		sendData.huifuuser = userId;
		sendData.id = fankuiid;
		sendData.shopcode = shopcode;
		sendData.pandianid = pandianid;
		sendData.pjId = sessionStorage.getItem("mobile");
		sendData.pingjiaUserName = sessionStorage.getItem("name");
//		sendData.pingjiaUserName = sessionStorage.getItem("name");
		sendData.pingjiaUser = sessionStorage.getItem("userId");
		sendData.wanchenguser = $('#wanchenguser'+fankuiid).val();
		if(sendData.wanchenguser == ''){
			sendData.wanchenguser = sendData.huifuuser;
		}
		sendData.wanchengusername = $('#wanchengusername'+fankuiid).val();
		if(sendData.wanchengusername == ''){
			sendData.wanchengusername = sendData.huifuusername;
		}
		sendData.ope = type;
		var huifuImg = [];
		$('#paizhaoHuifuUrl'+fankuiid).find('img[huifuimg]').each(function(j,el){
			huifuImg.push($(el).attr('src'));
		});
		sendData.huifuImg = huifuImg;
		var checkFLag = true;
		if(huifuFlag == 2){
			sendData.planDate = $('#planDate'+fankuiid).val();
			if(sendData.planDate == ''){
				checkFLag = false;
				layer.msg('预计完成时间不能为空');
			}
		}
		if(checkFLag){
			
			$.ajax({
				url: "../pandianevery/huifuPandianJianchaWentifankui"
					,type:'post'
						,dataType:'json'
							,async: false
							,contentType: "application/json; charset=utf-8"
								,data:JSON.stringify(sendData) 
								,success: function(res){
									console.log(res)
									if(res.success){
//									history.go(-1);
										window.location.href='toJiancha_pandian_daibanshixiang';
									}else{
										hideloading();
										layer.alert(res.message);
									}
								}
			});
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}
}

function xiugai(){
	showloading();
	try {
		var sendData = {};
		var insertArray = [];
		var checkFlag = true;
		$('div[itemDiv]').each(function(i,obj){
			if(checkFlag){
				var insertJson = {};
				$(obj).find('[jsonKey]').each(function(j,el){
					if($(el).parent().find('span').text() == '*' && $(el).val() == ''){
						alert($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('jsonKey');
						insertJson[key] = $(el).val();
						//console.log(insertJson);
						key = null;
					}
				});
				if(insertJson.wenti == ''){
					alert("问题反馈不能为空");
					checkFlag = false;
					return false;
				}
				insertJson.pandianid = pandianid;
				insertJson.lrr = userId;
				insertJson.flag = 0;
				insertJson.shenpiFlag = '';
				insertArray.push(insertJson);
			}else{
				return false;
			}
		});
//		console.log(insertArray);
		if(checkFlag && insertArray.length > 0){
			sendData.wentiArray = insertArray;
//			sendData.querenFlag = 0;
//			sendData.flag = 0;
//			sendData.wanchengUser = userId;
			sendData.id=pandianid;
			sendData.pandianid=pandianid;
			sendData.querenFlag = 0;
			sendData.querenUser = sessionStorage.getItem("userId");
			sendData.shopcode = sessionStorage.getItem("shopcode");
			sendData.shopname = sessionStorage.getItem("shopname");
			sendData.flag = 4;
			sendData.wanchengUser = sessionStorage.getItem("userId");
			sendData.wanchengUsername = sessionStorage.getItem("name");
			$.ajax({
				url: "../pandianevery/updatePandianJianchaWentifankui"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.success){
						window.location.href='toJiancha_pandian_daibanshixiang';
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	
}

function addoperation(){
	if(type == 'xiugai'){
		$('#saveButton').show();
		$('#saveButton').append('<div class="submit_button w94">提交</div> ');
		$('#saveButton').off('click');
		$('#saveButton').on('click',xiugai);
		
	}else{
		$('#addButton').show();
		$('#addButton').append(
				'<div class="submit_button w94 bg_red">'
				+'<span  style="display:inline-block; width:16px; height:16px!important; line-height:14px!important; font-weight:600; font-size:15px; text-align:center; border:1px #fff solid; border-radius:10px; color:#fff!important;">+</span>'
				+'新增问题反馈</div>'
		);
		$('#saveButton').show();
		$('#saveButton').append('<div class="submit_button w94">提交</div> ');
		$('#saveButton').off('click');
		$('#saveButton').on('click',saveInfo);
	}
}
//打开钉钉人员选择
function openDingdingUser(index){
	
	dd.ready(function(){
//		dd.biz.contact.complexPicker({
//		    title:"选择发送人",            //标题
//		    corpId:"dingf27fbe68f154064235c2f4657eb6378f",              //企业的corpId _config.corpId
//		    multiple:false,            //是否多选
//		    limitTips:"只能选择1个",          //超过限定人数返回提示
//		    maxUsers:1,            //最大可选人数
//		    pickedUsers:[],            //已选用户
//		    pickedDepartments:[],          //已选部门
//		    disabledUsers:[],            //不可选用户
//		    disabledDepartments:[],        //不可选部门
//		    requiredUsers:[],            //必选用户（不可取消选中状态）
//		    requiredDepartments:[],        //必选部门（不可取消选中状态）
//		    appId:275020788,              //微应用的Id _config.appid
//		    permissionType:"GLOBAL",          //可添加权限校验，选人权限，目前只有GLOBAL这个参数
//		    responseUserOnly:true,        //返回人，或者返回人和部门
//		    startWithDepartmentId:0 ,   //仅支持0和-1
//		    onSuccess: function(result) {
//		    	$('#senduser'+index).val(result.users[0].emplId);
//		    	$('#sendusername'+index).val(result.users[0].name);
//		        /**
//		        {
//		            selectedCount:1,                              //选择人数
//		            users:[{"name":"","avatar":"","emplId":""}]，//返回选人的列表，列表中的对象包含name（用户名），avatar（用户头像），emplId（用户工号）三个字段
//		            departments:[{"id":,"name":"","number":}]//返回已选部门列表，列表中每个对象包含id（部门id）、name（部门名称）、number（部门人数）
//		        }
//		        */
//		    },
//		   onFail : function(err) {}
//		});
		dd.biz.customContact.choose({
		    title: '选择发送人', //标题
		    users: ['130766000021213385','2704413229068693','1517655033950584'
		            ,'151764065431366562'
		            ,'014720540838335664'
		            ,'1517606036859266'
		            ,'42666741783942'
		            ,'0236201665792188'
		            ,'151760201628523566'
		            ,'1517590400938140'
		            ,'1517601928940741'
		            ,'151757595935585656'
		            ,'050358241535729991'
		            ,'151760475421031965'
		            ,'022332356327157339'
		            ,'25184064702532'
		            ,'1745696322855573'],//一组员工userid
		    corpId: 'dingf27fbe68f154064235c2f4657eb6378f',//加密的企业 ID，
		    isShowCompanyName: true,   //true|false，默认为 false
	//	    disabledUsers: ["78308"], //不能选的人
		    onSuccess: function(result) {
		    	$('#senduser'+index).val(result[0].emplId);
		    	$('#sendusername'+index).val(result[0].name);
		    /* data结构
		      [{
		        "name": "张三", //姓名
		        "avatar": "http://g.alicdn.com/avatar/zhangsan.png" //头像图片url，可能为空
		        "emplId": '0573', //即员工userId，[<font color=red>获取成员详情接口</font>](https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.DHPTF8&treeId=385&articleId=106816&docType=1#s1)
	
		       },
		       ...
		      ]
		    */
		    },
		    onFail : function(err) {}
		});
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//完成人员选择
function openwanchengUser(index){
	
	dd.ready(function(){
		dd.biz.contact.complexPicker({
		    title:"选择完成人",            //标题
		    corpId:"dingf27fbe68f154064235c2f4657eb6378f",              //企业的corpId _config.corpId
		    multiple:false,            //是否多选
		    limitTips:"只能选择1个",          //超过限定人数返回提示
		    maxUsers:1,            //最大可选人数
		    pickedUsers:[],            //已选用户
		    pickedDepartments:[],          //已选部门
		    disabledUsers:[],            //不可选用户
		    disabledDepartments:[],        //不可选部门
		    requiredUsers:[],            //必选用户（不可取消选中状态）
		    requiredDepartments:[],        //必选部门（不可取消选中状态）
		    appId:275020788,              //微应用的Id _config.appid
		    permissionType:"GLOBAL",          //可添加权限校验，选人权限，目前只有GLOBAL这个参数
		    responseUserOnly:true,        //返回人，或者返回人和部门
		    startWithDepartmentId:0 ,   //仅支持0和-1
		    onSuccess: function(result) {
		    	$('#wanchenguser'+index).val(result.users[0].emplId);
		    	$('#wanchengusername'+index).val(result.users[0].name);
		        /**
		        {
		            selectedCount:1,                              //选择人数
		            users:[{"name":"","avatar":"","emplId":""}]，//返回选人的列表，列表中的对象包含name（用户名），avatar（用户头像），emplId（用户工号）三个字段
		            departments:[{"id":,"name":"","number":}]//返回已选部门列表，列表中每个对象包含id（部门id）、name（部门名称）、number（部门人数）
		        }
		        */
		    },
		   onFail : function(err) {}
		});
		
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//打开钉钉拍照
function openphoto(index){
	
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: nowDate,
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
				$('#paizhapoUrl'+index+' .clearfix').remove()
				$('#paizhapoUrl'+index).append('<div class="wig_img">'
						+'<div class="img_box">'
						+'<img wentiimg alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						+'</div>');
				$('#paizhapoUrl'+index).append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//打开钉钉拍照
function openphotohuifu(index){
	
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: nowDate,
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
				$('#paizhaoHuifuUrl'+index+' .clearfix').remove()
				$('#paizhaoHuifuUrl'+index).append('<div class="wig_img">'
						+'<div class="img_box">'
						+'<img huifuimg alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						+'</div>');
				$('#paizhaoHuifuUrl'+index).append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().parent().index();
	    		$(obj).parent().parent().remove();
	    		photoUrl.splice(index,1);
	    	}
	        
	    },
	    onFail : function(err) {}
	});
	 
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: imgOne.split(','),//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}
